<template>
  <div class="category-container">
    <el-card class="category-card">
      <template #header>
        <div class="card-header">
          <el-radio-group v-model="activeType" size="large">
            <el-radio-button label="type">类型分类</el-radio-button>
            <el-radio-button label="package">套餐分类</el-radio-button>
            <el-radio-button label="brand">品牌分类</el-radio-button>
          </el-radio-group>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>新增分类
          </el-button>
        </div>
      </template>

      <!-- 分类表格 -->
      <el-table :data="categoryList" style="width: 100%" v-loading="loading">
        <el-table-column prop="name" label="分类名称" min-width="150" />
        <el-table-column prop="code" label="分类编码" width="120" />
        <el-table-column prop="sort" label="排序" width="80" align="center" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑分类弹窗 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="分类编码" prop="code">
          <el-input v-model="formData.code" placeholder="请输入分类编码" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="formData.status"
            :active-value="1"
            :inactive-value="0"
            :disabled="isAdd"
          />
        </el-form-item>

        <!-- 套餐分类特有字段 -->
        <template v-if="activeType === 'package'">
          <el-form-item label="优惠力度" prop="discount">
            <el-input-number 
              v-model="formData.discount"
              :min="0"
              :max="100"
              :precision="1"
              :step="0.1"
            >
              <template #suffix>%</template>
            </el-input-number>
          </el-form-item>
          <el-form-item label="包含类型" prop="includeTypes">
            <el-select
              v-model="formData.includeTypes"
              multiple
              placeholder="请选择包含的家具类型"
            >
              <el-option
                v-for="item in typeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="套餐规则" prop="rules">
            <el-input
              v-model="formData.rules"
              type="textarea"
              rows="3"
              placeholder="请输入套餐规则说明"
            />
          </el-form-item>
          <el-form-item label="推荐搭配">
            <el-table :data="formData.recommendations" border>
              <el-table-column type="index" width="50" label="序号" />
              <el-table-column prop="type" label="家具类型">
                <template #default="{ row }">
                  <el-select v-model="row.type" placeholder="请选择类型">
                    <el-option
                      v-for="item in formData.includeTypes"
                      :key="item"
                      :label="item"
                      :value="item"
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="quantity" label="建议数量" width="120">
                <template #default="{ row }">
                  <el-input-number
                    v-model="row.quantity"
                    :min="1"
                    :precision="0"
                    controls-position="right"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="remark" label="备注说明">
                <template #default="{ row }">
                  <el-input v-model="row.remark" placeholder="请输入备注" />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template #default="{ $index }">
                  <el-button
                    link
                    type="danger"
                    @click="removeRecommendation($index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="table-footer">
              <el-button type="primary" link @click="addRecommendation">
                <el-icon><Plus /></el-icon>添加推荐
              </el-button>
            </div>
          </el-form-item>
        </template>

        <el-form-item label="描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            rows="3"
            placeholder="请输入分类描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

// 分类类型
const activeType = ref<'type' | 'package' | 'brand'>('type')
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 表单相关
const dialogVisible = ref(false)
const isAdd = ref(true)
const submitting = ref(false)

// 类型选项
const typeOptions = [
  { value: '客厅家具', label: '客厅家具' },
  { value: '卧室家具', label: '卧室家具' },
  { value: '餐厅家具', label: '餐厅家具' },
  { value: '书房家具', label: '书房家具' }
]

// 模拟数据
const categoryList = ref([
  {
    id: '1',
    name: '客厅家具',
    code: 'KT001',
    sort: 1,
    status: 1,
    createTime: '2023-11-28 10:00:00',
    description: '客厅家具分类'
  },
  {
    id: '2',
    name: '卧室家具',
    code: 'WS001',
    sort: 2,
    status: 1,
    createTime: '2023-11-28 10:00:00',
    description: '卧室家具分类'
  }
])

// 表单数据
const formData = ref({
  id: '',
  name: '',
  code: '',
  sort: 0,
  status: 1,
  description: '',
  discount: 90,
  includeTypes: [] as string[],
  rules: '',
  recommendations: [] as any[]
})

const formRules = {
  name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入分类编码', trigger: 'blur' }],
  sort: [{ required: true, message: '请输入排序号', trigger: 'blur' }]
}

const dialogTitle = computed(() => (isAdd.value ? '新增分类' : '编辑分类'))

// 方法
const handleAdd = () => {
  isAdd.value = true
  dialogVisible.value = true
  formData.value = {
    id: '',
    name: '',
    code: '',
    sort: 0,
    status: 1,
    description: '',
    discount: 90,
    includeTypes: [],
    rules: '',
    recommendations: []
  }
}

const handleEdit = (row: any) => {
  isAdd.value = false
  dialogVisible.value = true
  formData.value = { ...row }
}

const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除该分类吗？', '提示', {
      type: 'warning'
    })
    ElMessage.success('删除成功')
    loadData()
  } catch {}
}

const handleStatusChange = async (row: any) => {
  ElMessage.success('状态更新成功')
}

const handleSubmit = async () => {
  submitting.value = true
  try {
    ElMessage.success(`${isAdd.value ? '新增' : '编辑'}成功`)
    dialogVisible.value = false
    loadData()
  } catch (error) {
    console.error('保存失败：', error)
  } finally {
    submitting.value = false
  }
}

const resetForm = () => {
  formData.value = {
    id: '',
    name: '',
    code: '',
    sort: 0,
    status: 1,
    description: '',
    discount: 90,
    includeTypes: [],
    rules: '',
    recommendations: []
  }
}

const loadData = () => {
  loading.value = true
  setTimeout(() => {
    total.value = categoryList.value.length
    loading.value = false
  }, 500)
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  loadData()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadData()
}

const addRecommendation = () => {
  formData.value.recommendations.push({
    type: '',
    quantity: 1,
    remark: ''
  })
}

const removeRecommendation = (index: number) => {
  formData.value.recommendations.splice(index, 1)
}

// 初始化
loadData()
</script>

<style scoped lang="scss">
.category-container {
  .category-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

.table-footer {
  margin-top: 10px;
  text-align: center;
}

// 扩展弹窗宽度
:deep(.el-dialog) {
  .el-dialog__body {
    max-height: 60vh;
    overflow-y: auto;
  }
}
</style> 